package com.chenjt.juc.nine_atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/12 9:48
 */
class MyNumber{

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus(){
        atomicInteger.getAndIncrement();
    }


}

public class AtomicIntegerDemo {

    public static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {

        MyNumber myNumber = new MyNumber();

        CountDownLatch countDownLatch = new CountDownLatch(SIZE);

        // 50个线程，每个线程都对atomicInteger做一次+1
        for(int i = 0;i<SIZE;i++){
            new Thread(()->{
                try {
                    for(int j=1;j<=1000;j++){
                        myNumber.addPlusPlus();
                    }
                } finally {
                    // 等该线程全部计算完成了，countDownLatch就减1
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }


        // 等待上面50个线程全部计算完成后，再去获取最终值
        /*try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+"\t"+ "result:" + myNumber.atomicInteger.get());


    }



}
